using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyManager : MonoBehaviour
{
    // 单例模式
    public static EnemyManager Instance { get; private set; }

    [Header("刷新点")]
    public Transform[] spawnPoints;  // 敌人生成点数组

    [Header("巡逻点数组")]
    public Transform[] patrolPoints; // 敌人巡逻点数组

    [Header("敌人波次")]
    public List<EnemyWave> enemyWaves;   // 敌人波次列表

    private int currentWaveIndex = 0;     // 当前波次索引
    private int enemyCount = 0;            // 敌人计数
    public GameObject portalPrefab; //传送门预制体

    // 判断是否为最后一波
    public bool GetLastWave() => currentWaveIndex == enemyWaves.Count - 1;

    private void Awake()
    {
        Instance = this;
    }

    private void Start()
    {
        StartCoroutine(nameof(startNextWaveCoroutine));
    }

    public void KillEnemy(Transform tf)
    {

        enemyCount--;
        if (enemyCount == 0)// 敌人死亡
        {
            if (GetLastWave())
            {
                if (portalPrefab)
                {
                    Debug.Log("通关");
                    //生成传送门
                    Instantiate(portalPrefab, tf.position, Quaternion.identity);
                }
                else
                {
                    Debug.Log("游戏胜利");
                }

                return;
            }
            //开始下一波敌人
            currentWaveIndex++; // 当前波次索引增加
            StartCoroutine(nameof(startNextWaveCoroutine));
        }
    }

    // 开始下一波的协程
    IEnumerator startNextWaveCoroutine()
    {
        List<EnemyData> enemies = enemyWaves[currentWaveIndex].enemies; // 获取当前波次对应的敌人列表
        foreach (EnemyData enemyData in enemies)
        {
            for (int i = 0; i < enemyData.waveEnemyCount; i++)
            {
                enemyCount++;
                // 实例化敌人预制体，并设置位置为随机的刷新点
                GameObject enemy = Instantiate(enemyData.enemyPrefab, GetRandomSpawnPoint(), Quaternion.identity);

                if (patrolPoints != null) // 如果巡逻点数组不为空，将巡逻点数组赋值给敌人的巡逻点数组
                {
                    enemy.GetComponent<Enemy.FSM>().parameter.patrolPoints = patrolPoints;
                }

                yield return new WaitForSeconds(enemyData.spawnInterval); // 等待生成下一个敌人的间隔时间
            }
        }
    }

    // 获取随机刷新点
    private Vector3 GetRandomSpawnPoint()
    {
        int randomIndex = Random.Range(0, spawnPoints.Length); // 随机选择一个刷新点的索引
        return spawnPoints[randomIndex].position; // 返回随机刷新点的位置
    }
}

// 由于没有继承MonoBehaviour，所以需要加上[System.Serializable]以在Unity编辑器中序列化
[System.Serializable]
public class EnemyData
{
    public GameObject enemyPrefab;  // 敌人预制体
    public float spawnInterval;     // 生成间隔
    public float waveEnemyCount;    // 波次敌人数量
}

[System.Serializable]
public class EnemyWave
{
    public List<EnemyData> enemies; // 每波的敌人列表
}
